package com.zhn.usermanager.exception;

import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @author thinknovo
 * @version 1.0
 */
@RestControllerAdvice    //  @RestControllerAdvice  和 @ControllerAdvice
public class SpringMVCException {  //  Advice 通知的意思
    @ExceptionHandler(NumberFormatException.class)  // 官方英文原意：这样的捕获状态不够优雅
    public Map<String, Object> numberFormatException(Throwable throwable) {   // 异常处理的方法返回类型，通常与所有其余的方法返回类型一致，并且包含前端解析的固定核心字段key，比如(code、msg....)
        throwable.printStackTrace();
        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        stringObjectHashMap.put("code", 500);
        stringObjectHashMap.put("msg", throwable.getMessage());
        return stringObjectHashMap;
    }

    @ExceptionHandler(FileNotFoundException.class)  // 官方英文原意：这样的捕获状态不够优雅
    public Map<String, Object> fileNotFoundException(Throwable throwable) {   // 异常处理的方法返回类型，通常与所有其余的方法返回类型一致，并且包含前端解析的固定核心字段key，比如(code、msg....)
        throwable.printStackTrace();
        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        stringObjectHashMap.put("code", 500);
        stringObjectHashMap.put("msg", Arrays.toString(throwable.getStackTrace()));
        return stringObjectHashMap;
    }

    @ExceptionHandler(ClassNotFoundException.class)
    public Map<String, Object> classNotFoundException(Throwable throwable) {
        throwable.printStackTrace();
        HashMap<String, Object> map = new HashMap<>();
        map.put("code", 500);
        map.put("msg", "对不起！服务器驱动出错");
        return map;
    }

    @ExceptionHandler(SQLException.class)
    public Map<String, Object> sQLException(Throwable throwable) {
        throwable.printStackTrace();
        HashMap<String, Object> map = new HashMap<>();
        map.put("code", 500);
        map.put("msg", "对不起！数据库操作失败");
        return map;
    }

    @ExceptionHandler(IOException.class)
    public Map<String, Object> iOException(Throwable throwable) {
        throwable.printStackTrace();
        HashMap<String, Object> map = new HashMap<>();
        map.put("code", 500);
        map.put("msg", "对不起！文件上传失败");
        return map;
    }
}
